<template>
  <n-modal
    v-model:show="isVisible"
    style="transform: translateY(25px)"
    class="m-auto max-w-700 min-w-345 f-c-c rounded-10 bg-white p-15 card-shadow"
    dark:bg-dark
    :mask-closable="false"
    :on-mask-click="handleTest"
  >
    <div relative w-330 flex-col px-20 py-35>
      <SvgIcon
        v-if="showCloseIcon"
        icon="close"
        color="black"
        class="absolute right-0 top-0 cursor-pointer"
        @click="$emit('close')"
      />
      <h3 color="#174CAD" mb-30 f-c-c text-28 font-bold>
        <img src="@/assets/images/logo-name.png" height="35" class="mr-10" />
        {{title}}
      </h3>
      <n-form ref="formRef" :model="loginInfo" :rules="rules">
        <n-form-item path="name" :show-label="false" mb-10>
          <n-input
            v-model:value="loginInfo.username"
            class="h-48 items-center text-16"
            placeholder="用户名"
            :maxlength="50"
          >
            <template #prefix>
              <icon-material-symbols:account-circle-outline class="mr-8 text-20 opacity-40" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password" :show-label="false">
          <n-input
            v-model:value="loginInfo.password"
            class="h-48 items-center text-16"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            :maxlength="20"
            @keydown.enter="handleLogin"
          >
            <template #prefix>
              <icon-ri:lock-password-line class="mr-8 text-20 opacity-40" />
            </template>
          </n-input>
        </n-form-item>

        <div flex gap-x-50>
          <n-button
            text
            class="p-10 dark:color-white"
            @click="register"
          >
            注册
          </n-button>
          <n-button
            text
            class="p-10 dark:color-white"
            @click="forget"
          >
            忘记密码
          </n-button>
        </div>


        <div mt-20>
          <n-button
            attr-type="submit"
            h-50
            w-full
            rounded-5
            text-16
            type="primary"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </n-button>
        </div>
      </n-form>
    </div>
  </n-modal>
</template>
<script setup>
import {ref, watch} from 'vue'
import { lStorage, setToken } from '@/utils'
import { useUserStore } from '@/store'
import { addDynamicRoutes } from '@/router'
import { useRouter, useRoute } from 'vue-router'
import { requiredRule } from '../utils/validator'
import sha256 from 'crypto-js/sha256'
import api from "@/api/admin";
import {List} from "echarts";
const userStore = useUserStore()
const emit = defineEmits(['updatePage', 'closeModal'])
const props = defineProps({
	title: {
		type: String,
		default: '龙腾',
	},
	successPath: {
		type: String,
		default: '',
	},
	showCloseIcon: {
		type: Boolean,
		default: true,
	},
	login: {
		type: Function,
		require: true,
	},
	show: {
		type: Boolean,
		required: true,
	}
})
const role=ref('')
const router = useRouter()
const { query } = useRoute()
const loginInfo = ref({
  username: '',
  password: '',
})
const formRef = ref(null)
const isVisible = ref(props.show)
const rules = {
  username: requiredRule('账号'),
  password: requiredRule('密码'),
}
initLoginInfo()
const handleTest = () => {
	emit("closeModal")
}
const register=()=>{
  router.push({name: 'AdminRegister'})
}
const forget=()=>{
  router.push({name:'AdminRePwInfo'})
}
function initLoginInfo() {
  const localLoginInfo = lStorage.get('loginInfo')
  if (localLoginInfo) {
    loginInfo.value.username = localLoginInfo.username || ''
    loginInfo.value.password = localLoginInfo.password || ''
  }
}
const loading = ref(false)
const data = ref(null)
async function handleLogin() {
  const { doLogout } = useUserStore()
  const { username, password } = loginInfo.value
  try {
    await formRef.value.validate()
    try {
      loading.value = true
      $message.loading('登录中...')
      const res = await props.login({
        username: username.trim(),
        password: password.trim().toString(),
      })
      console.log(res)
      doLogout() //先清空之前的登录状态(Admin端)

      setToken(res.data.token) //保存token
      await addDynamicRoutes() //动态增加路由

      role.value=userStore.getRole()
      $message.success('登录成功')
      emit('close')
      if (query.redirect) {
        const path = query.redirect
        Reflect.deleteProperty(query, 'redirect')
        router.push({ path, query })
      } else {
        if (props.successPath) {
          router.push({ path: props.successPath })
        }
      }
    } catch (error) {
      console.error(error)
      $message.removeMessage()
    }
    loading.value = false
  } catch (error) {
    console.error(error) //未通过前端验证
  }
}
const forgetName=()=>{
  window.open(
      `http://${window.location.host}/#/user/faq?expandItem=12&itemId=collapse12`,
      '_blank'
  )
}
const forgetPassword=()=>{
  window.open(
      `http://${window.location.host}/#/user/faq?expandItem=11&itemId=collapse11`,
      '_blank'
  )
}
watch(() => props.show, (newVal) => {
	isVisible.value = newVal;
});
</script>
